package org.example.leetcode.interview.math;

public class LC0029 {

    public int divide(int dividend, int divisor) {
        if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
        boolean negative = false;
        // 转成负数运算
        if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) negative = true;
        if (dividend > 0) dividend = -dividend;
        if (divisor > 0) divisor = -divisor;

        int LIMIT = Integer.MIN_VALUE >> 1; // MIN 的一半
        int ans = 0;
        while (dividend <= divisor) {
            int left = divisor, right = -1;
            while (left >= LIMIT && right >= LIMIT && left >= dividend - left) {
                left += left;
                right += right;
            }
            dividend -= left;
            ans += right;
        }

        return negative ? ans : -ans;
    }

    public static void main(String[] args) {
        System.out.println(Integer.MIN_VALUE >> 1);
    }
}
